﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Services;

namespace WebRole1
{
	public partial class WritePost : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			btnSubmit.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(btnSubmit, null).ToString());

			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["Username"] != null)
				{
					lblUsername.Visible = false;
					txtUsername.Visible = false;
				}
			}

			if (!IsPostBack)
			{
				//If this page is openend to write a reply or edit a message...
				//show the original posting
				ShowOriginalPost();
			}
		}




		/// <summary>
		/// If this page is openend to write a reply or edit a message...
		/// show the original posting
		/// </summary>
		private void ShowOriginalPost()
		{
			Int64? topicID = null;
			Int64? replyToID = null;
			Int64? editPostID = null;
			string urlTitle = "";

			//Get the values that are passed through in the url
			GetIDsFromUrl(ref topicID, ref replyToID, ref editPostID, ref urlTitle);

			if (replyToID.HasValue)
			{
				PostingService postingServ = new PostingService();
				DataSet dst = postingServ.getPost(replyToID.Value);

				string content = dst.Tables[0].Rows[0]["Content"].ToString();

				//Parse quote 1.1
				while (Regex.IsMatch(content, "<div class=\"quoteHeader\">([\\s\\S]*?)</div>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<div class=\"quoteHeader\">(?<inner>([\\s\\S]*?))</div>", "", RegexOptions.IgnoreCase);

				//Parse quote 1.2
				while (Regex.IsMatch(content, "<div class=\"quoteContent\">([\\s\\S]*?)</div>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<div class=\"quoteContent\">(?<inner>([\\s\\S]*?))</div>", "[...]", RegexOptions.IgnoreCase);

				//Parse hyperlink 1
				while (Regex.IsMatch(content, "<a href=\"([\\s\\S]*?)</a>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<a href=\"(?<inner>([\\s\\S]*?))\">(?<inner2>([\\s\\S]*?))</a>", "[url=${inner}]${inner2}[/url]", RegexOptions.IgnoreCase);

				//Parse bold 1
				while (Regex.IsMatch(content, "<b>([\\s\\S]*?)</b>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<b>(?<inner>([\\s\\S]*?))</b>", "[b]${inner}[/b]", RegexOptions.IgnoreCase);

				//Parse italic 1
				while (Regex.IsMatch(content, "<i>([\\s\\S]*?)</i>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<i>(?<inner>([\\s\\S]*?))</i>", "[i]${inner}[/i]", RegexOptions.IgnoreCase);

				//Parse strikethrough 1
				while (Regex.IsMatch(content, "<s>([\\s\\S]*?)</s>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<s>(?<inner>([\\s\\S]*?))</s>", "[s]${inner}[/s]", RegexOptions.IgnoreCase);

				//Parse underline 1
				while (Regex.IsMatch(content, "<u>([\\s\\S]*?)</u>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<u>(?<inner>([\\s\\S]*?))</u>", "[u]${inner}[/u]", RegexOptions.IgnoreCase);

				//Parse image 1
				while (Regex.IsMatch(content, "<img src=\"([\\s\\S]*?)</img>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<img src=\"(?<inner>([\\s\\S]*?))\"</img>", "[ [url=${inner}]afbeelding[/url] ]", RegexOptions.IgnoreCase);

				//Parse break
				content = content.Replace("<br/>", "\n");


				DateTime postDate = DateTime.Parse(dst.Tables[0].Rows[0]["Timestamp"].ToString());

				string dow = postDate.ToString("dddd", new System.Globalization.CultureInfo("nl-NL"));
				txtNewMsg.Text = "[quote][b]Op " + dow + " " + dst.Tables[0].Rows[0]["Timestampshort"].ToString() + " schreef " + dst.Tables[0].Rows[0]["Username"].ToString() + ":[/b]\n" + content + "\n[/quote]\n";
			}
			else if (editPostID.HasValue)
			{
				PostingService postingServ = new PostingService();
				DataSet dst = postingServ.getPost(editPostID.Value);

				string content = Server.HtmlDecode(dst.Tables[0].Rows[0]["Content"].ToString());

				//Parse quote 2.1 - Same code as Parse quote 1.1
				while (Regex.IsMatch(content, "<div class=\"quoteHeader\">([\\s\\S]*?)</div>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<div class=\"quoteHeader\">(?<inner>([\\s\\S]*?))</div>", "", RegexOptions.IgnoreCase);

				//Parse quote 2.2 - Other code than Parse quote 1.2
				while (Regex.IsMatch(content, "<div class=\"quoteContent\">([\\s\\S]*?)</div>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<div class=\"quoteContent\">(?<inner>([\\s\\S]*?))</div>", "[quote]${inner}[/quote]<br/>", RegexOptions.IgnoreCase);

				//Parse hyperlink 2 - Same as Parse hyperlink 1
				while (Regex.IsMatch(content, "<a href=\"([\\s\\S]*?)</a>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<a href=\"(?<inner>([\\s\\S]*?))\">(?<inner2>([\\s\\S]*?))</a>", "[url=${inner}]${inner2}[/url]", RegexOptions.IgnoreCase);



				while (Regex.IsMatch(content, "<b>([\\s\\S]*?)</b>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<b>(?<inner>([\\s\\S]*?))</b>", "[b]${inner}[/b]", RegexOptions.IgnoreCase);

				while (Regex.IsMatch(content, "<i>([\\s\\S]*?)</i>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<i>(?<inner>([\\s\\S]*?))</i>", "[i]${inner}[/i]", RegexOptions.IgnoreCase);

				while (Regex.IsMatch(content, "<s>([\\s\\S]*?)</s>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<s>(?<inner>([\\s\\S]*?))</s>", "[s]${inner}[/s]", RegexOptions.IgnoreCase);

				while (Regex.IsMatch(content, "<u>([\\s\\S]*?)</u>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<u>(?<inner>([\\s\\S]*?))</u>", "[u]${inner}[/u]", RegexOptions.IgnoreCase);

				while (Regex.IsMatch(content, "<img src=\"([\\s\\S]*?)</img>", RegexOptions.IgnoreCase))
					content = Regex.Replace(content, "<img src=\"(?<inner>([\\s\\S]*?))\"</img>", "[img]${inner}[/img]", RegexOptions.IgnoreCase);



				content = content.Replace("<br/>", "\n");

				txtNewMsg.Text = content;
			}
			else
			{
				Response.Redirect("start.aspx");
			}
		}

		/// <summary>
		/// Read the values that are passed through in the url
		/// and return them through reference variables
		/// </summary>
		/// <param name="topicID"></param>
		/// <param name="replyToID"></param>
		/// <param name="editPostID"></param>
		private static void GetIDsFromUrl(ref Int64? topicID, ref Int64? replyToID, ref Int64? editPostID, ref string urlTitle)
		{
			if (HttpContext.Current.Request.QueryString["Topic"] != null)
			{
				topicID = Int64.Parse(HttpContext.Current.Request.QueryString["Topic"].ToString());
			}

			if (HttpContext.Current.Request.QueryString["ReplyTo"] != null)
			{
				replyToID = Int64.Parse(HttpContext.Current.Request.QueryString["ReplyTo"].ToString());
			}

			if (HttpContext.Current.Request.QueryString["Edit"] != null)
			{
				editPostID = Int64.Parse(HttpContext.Current.Request.QueryString["Edit"].ToString());
			}

			if (HttpContext.Current.Request.QueryString["urltitle"] != null)
			{
				urlTitle = HttpContext.Current.Request.QueryString["urltitle"].ToString();
			}
		}


		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			Int64? topicID = null;
			Int64? replyToID = null;
			Int64? editPostID = null;
			string urlTitle = "";
			string username = "";


			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["Username"] != null)
				{
					username = aCookie["Username"];
				}
			}

			if (username == "")
			{
				if (txtUsername.Text.Trim() == "")
				{
					username = "Anonymous";
				}
				else
				{
					username = txtUsername.Text.Trim();
				}
			}




			if (txtNewMsg.Text.Trim() == "")
			{
				lblError.Text = "Type een bericht dat u wilt plaatsen";
				return;
			}



			//Get the values that are passed through in the url
			GetIDsFromUrl(ref topicID, ref replyToID, ref editPostID, ref urlTitle);


			if (editPostID.HasValue)
			{
				string message = Server.HtmlEncode(txtNewMsg.Text);

				PostingService postingServ = new PostingService();
				postingServ.UpdatePosting(message, editPostID.Value);

				Response.Redirect("~/topic/" + topicID.ToString() + "/0/" + urlTitle);
				//Response.Redirect("~/ViewTopic.aspx?id=" + topicID + "&page=0");
			}
			else if (topicID.HasValue)
			{
				string message = Server.HtmlEncode(txtNewMsg.Text);

				PostingService postingServ = new PostingService();


				try
				{
					string postid = "";
					int postcount;
					string ipaddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
					postingServ.InsertPosting(message, topicID.Value, username, Utils.GetUserID(Request), ipaddress, out postid, out postcount);
					Response.Redirect("~/topic/" + topicID.ToString() + "/0/" + urlTitle);
					//Response.Redirect("~/ViewTopic.aspx?id=" + topicID + "&page=0");
				}
				catch (Exception ex)
				{
					lblError.Text = ex.Message;
				}



				//PostingService postingServ = new PostingService();
				//DataSet dst = postingServ.getPost(replyToID.Value);

				//txtNewMsg.Text = "[quote]Op " + dst.Tables[0].Rows[0]["Timestamp"].ToString() + " schreef " + dst.Tables[0].Rows[0]["Username"].ToString() + ":\n" + dst.Tables[0].Rows[0]["Content"].ToString() + "[/quote]\n";
			}
			else
			{
				Response.Redirect("start.aspx");
			}
		}
	}
}